package com.yeqing.thread;

import java.util.concurrent.locks.ReentrantLock;

public class ThreadInterruptDemo {

    public static ReentrantLock reentrantLock = new ReentrantLock();

    public static void main(String[] args) throws InterruptedException {

        ThreadTask threadTask = new ThreadTask(reentrantLock);

        Thread thread1 = new Thread(threadTask);
        Thread thread2 = new Thread(() -> {
            System.out.println("t2 ==== 进入" + System.nanoTime());

            try {
                try {
                    reentrantLock.lock();
                    System.out.println("t2 执行了");
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException();
                }
            } finally {
                reentrantLock.unlock();
            }
            System.out.println("t2 === " + System.nanoTime());
        });

        thread1.start();
        Thread.sleep(1000);
        thread2.start();
        Thread.sleep(1000);

        thread1.interrupt();
    }




}

class ThreadTask implements Runnable {
    ReentrantLock reentrantLock;
    public ThreadTask(ReentrantLock reentrantLock) {
        this.reentrantLock = reentrantLock;
    }
    @Override
    public void run() {
        System.out.println("t1 ==== " + System.nanoTime());

        try {
            reentrantLock.lock();
            System.out.println("t1 执行了");
            while (true) {
                // 一直执行任务
                if (Thread.currentThread().isInterrupted()) {
                    throw new RuntimeException();
                }
            }
        } finally {
            reentrantLock.unlock();
        }
    }
}